/**
 * @desc    业务线配置信息
 * @author  刘贺[of2220]
 * @company qianmi.com
 * @Date    2017/2/10
 */
('use strict');

import BusinessConfigModel from '../dao/businessConfig/business-config-model';
import * as Immutable from 'immutable';

interface BusCfgInterface {
  editedInPC?: boolean;
}

export default class BusinessConfigService {
  static initConfigInfo(siteId) {
    const info = {
      siteInfo: siteId,
      editedInPC: false
    };
    return new Promise((resolve, reject) => {
      new BusinessConfigModel(info).save((err, data) => {
        err ? reject(err) : resolve(data);
      });
    });
  }
  /**
     * 获取全量配置信息
     * @param siteId
     * @returns {Promise<T>}
     */
  static getDetailCfgInfo(siteId) {
    return new Promise((resolve, reject) => {
      BusinessConfigModel.findOne({ siteInfo: siteId }).lean().exec((err, data) => {
        err ? reject(err) : resolve(data);
      });
    });
  }

  /**
     * 获取指定的配置信息
     * @param siteId
     * @param path
     * @returns {Promise<T>}
     */
  static getBusCfgInfo(siteId, path) {
    return new Promise((resolve, reject) => {
      BusinessConfigModel.findOne({ siteInfo: siteId }).select(path).lean().exec((err, data) => {
        if (err) {
          reject(err);
        } else {
          let result = {};
          let configInfo = Immutable.fromJS(data || {});
          let targetArr = path.split(' ');
          for (let i = 0, len = targetArr.length; i < len; i++) {
            let target = targetArr[i];
            let targetPath = target.split('.');
            let targetValue = configInfo.getIn(targetPath);
            result[target] = targetValue && targetValue.toJS ? targetValue.toJS() : targetValue;
          }
          resolve(result);
        }
      });
    });
  }

  /**
     * 更新指定配置信息
     * @param siteId
     * @param cfgInfo
     * @returns {Promise<T>}
     */
  static updateBusCfgInfo(siteId, cfgInfo: BusCfgInterface) {
    return new Promise((resolve, reject) => {
      BusinessConfigModel.findOneAndUpdate(
        { siteInfo: siteId },
        { $set: cfgInfo },
        { upsert: true }
      ).exec((err, data) => {
        err ? reject(err) : resolve(data);
      });
    });
  }
}
